<template>
  <div class="text-editor-app">
    <div class="editor-toolbar">
      <div class="toolbar-group">
        <el-button-group>
          <el-button
            type="default"
            :class="{ 'is-active': fontStyle.bold }"
            @click="toggleStyle('bold')"
          >
            <el-icon><Bold /></el-icon>
          </el-button>
          <el-button
            type="default"
            :class="{ 'is-active': fontStyle.italic }"
            @click="toggleStyle('italic')"
          >
            <el-icon><Italic /></el-icon>
          </el-button>
          <el-button
            type="default" 
            :class="{ 'is-active': fontStyle.underline }"
            @click="toggleStyle('underline')"
          >
            <el-icon><Underline /></el-icon>
          </el-button>
        </el-button-group>
      </div>
      
      <div class="toolbar-group">
        <el-button-group>
          <el-button
            type="default"
            :class="{ 'is-active': textAlign === 'left' }"
            @click="textAlign = 'left'"
          >
            <el-icon><AlignLeft /></el-icon>
          </el-button>
          <el-button
            type="default"
            :class="{ 'is-active': textAlign === 'center' }"
            @click="textAlign = 'center'"
          >
            <el-icon><AlignCenter /></el-icon>
          </el-button>
          <el-button
            type="default"
            :class="{ 'is-active': textAlign === 'right' }"
            @click="textAlign = 'right'"
          >
            <el-icon><AlignRight /></el-icon>
          </el-button>
        </el-button-group>
      </div>
      
      <div class="toolbar-group">
        <el-select v-model="fontSize" size="small" style="width: 100px">
          <el-option label="12px" value="12px" />
          <el-option label="14px" value="14px" />
          <el-option label="16px" value="16px" />
          <el-option label="18px" value="18px" />
          <el-option label="20px" value="20px" />
          <el-option label="24px" value="24px" />
        </el-select>
      </div>
      
      <div class="toolbar-group">
        <el-color-picker v-model="textColor" size="small" show-alpha />
      </div>
      
      <div class="toolbar-spacer"></div>
      
      <div class="toolbar-group">
        <el-button-group>
          <el-button @click="saveContent" type="primary">
            <el-icon><Download /></el-icon> 保存
          </el-button>
          <el-button @click="clearContent" type="danger">
            <el-icon><Delete /></el-icon> 清空
          </el-button>
        </el-button-group>
      </div>
    </div>
    
    <div class="editor-container">
      <div
        class="editor-content"
        contenteditable="true"
        ref="editorRef"
        @input="handleInput"
        :style="{
          fontWeight: fontStyle.bold ? 'bold' : 'normal',
          fontStyle: fontStyle.italic ? 'italic' : 'normal',
          textDecoration: fontStyle.underline ? 'underline' : 'none',
          textAlign: textAlign,
          fontSize: fontSize,
          color: textColor
        }"
      ></div>
    </div>
    
    <div class="status-bar">
      <span>字数: {{ wordCount }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { 
  Edit as Bold, 
  EditPen as Italic, 
  Brush as Underline, 
  ArrowLeft as AlignLeft, 
  Operation as AlignCenter, 
  ArrowRight as AlignRight, 
  Download,
  Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 编辑器引用
const editorRef = ref<HTMLDivElement | null>(null)

// 文本内容
const content = ref('')

// 字数统计
const wordCount = ref(0)

// 字体样式
const fontStyle = reactive({
  bold: false,
  italic: false,
  underline: false
})

// 文本对齐
const textAlign = ref<'left' | 'center' | 'right'>('left')

// 字体大小
const fontSize = ref('16px')

// 文本颜色
const textColor = ref('#333333')

// 本地存储键
const STORAGE_KEY = 'text-editor-content'

// 切换样式
const toggleStyle = (style: 'bold' | 'italic' | 'underline') => {
  fontStyle[style] = !fontStyle[style]
}

// 处理输入事件
const handleInput = () => {
  if (editorRef.value) {
    content.value = editorRef.value.innerHTML
    wordCount.value = countWords(editorRef.value.textContent || '')
    saveContentToLocalStorage()
  }
}

// 计算字数
const countWords = (text: string) => {
  // 简单实现，按空格和标点符号分割
  return text.trim().length > 0 ? text.trim().length : 0
}

// 保存内容到本地存储
const saveContentToLocalStorage = () => {
  const data = {
    content: content.value,
    fontStyle,
    textAlign: textAlign.value,
    fontSize: fontSize.value,
    textColor: textColor.value
  }
  localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
}

// 从本地存储加载内容
const loadContentFromLocalStorage = () => {
  const savedData = localStorage.getItem(STORAGE_KEY)
  if (savedData) {
    try {
      const data = JSON.parse(savedData)
      content.value = data.content || ''
      
      if (data.fontStyle) {
        fontStyle.bold = !!data.fontStyle.bold
        fontStyle.italic = !!data.fontStyle.italic
        fontStyle.underline = !!data.fontStyle.underline
      }
      
      textAlign.value = data.textAlign || 'left'
      fontSize.value = data.fontSize || '16px'
      textColor.value = data.textColor || '#333333'
      
      if (editorRef.value) {
        editorRef.value.innerHTML = content.value
        wordCount.value = countWords(editorRef.value.textContent || '')
      }
    } catch (e) {
      console.error('Failed to parse text editor content from localStorage', e)
    }
  }
}

// 保存内容
const saveContent = () => {
  saveContentToLocalStorage()
  ElMessage.success('内容已保存')
  
  // 提供下载功能
  const text = editorRef.value?.textContent || ''
  if (text.trim()) {
    const blob = new Blob([text], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `文档_${new Date().toISOString().slice(0, 10)}.txt`
    a.click()
    URL.revokeObjectURL(url)
  }
}

// 清空内容
const clearContent = () => {
  ElMessageBox.confirm('确定要清空当前内容吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (editorRef.value) {
      editorRef.value.innerHTML = ''
      content.value = ''
      wordCount.value = 0
      saveContentToLocalStorage()
      ElMessage.success('内容已清空')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 初始化
onMounted(() => {
  nextTick(() => {
    loadContentFromLocalStorage()
  })
})
</script>

<style scoped>
.text-editor-app {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.editor-toolbar {
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.toolbar-group {
  display: flex;
  align-items: center;
}

.toolbar-spacer {
  flex: 1;
}

.is-active {
  background-color: #ecf5ff;
  color: #409eff;
  border-color: #c6e2ff;
}

.editor-container {
  flex: 1;
  overflow: auto;
  padding: 20px;
}

.editor-content {
  min-height: 100%;
  outline: none;
  line-height: 1.5;
  white-space: pre-wrap;
}

.status-bar {
  padding: 8px 16px;
  background-color: #f5f7fa;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #606266;
}

@media (max-width: 768px) {
  .editor-toolbar {
    justify-content: center;
  }
  
  .toolbar-spacer {
    display: none;
  }
}
</style> 